var resumeData = JSON.parse(localStorage.getItem('resumeData'));
var updateResumeBtn = document.getElementById('updateResume');
updateResumeBtn.addEventListener('click', function () {
  event.preventDefault();
  const form = document.getElementById('userForm');
  const formData = new FormData(form);
  const resumeData = {};
  formData.forEach(function (value, key) {
    resumeData[key] = value;
  });
  const usersId = localStorage.getItem('userId');
  if (!usersId) {
    alert('未获取到用户ID，请重新登录或检查数据');
    return;
  }
  const content = JSON.stringify(resumeData);
  fetch(`http://192.168.244.14:8080/resumeStatus/update/${usersId}`, {
    method: 'PUT',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({ content, id: parseInt(usersId), updater: parseInt(usersId) })
  })
    .then(response => {
      if (!response.ok) {
        throw new Error('网络响应错误：' + response.status);
      }
      return response.json();
    })
    .then(data => {
      console.log('后端返回的数据:', data);
      if (data && data.code === 1) {
        alert('简历修改成功');
        window.location.href = "http://127.0.0.1:5501/sparkResume/html/users-function1.html";
      } else {
        alert('简历修改失败：' + (data && data.msg ? data.msg : '未知错误'));
      }
    })
    .catch(error => {
      console.error('修改简历请求出错:', error);
    });
});


window.onload = function () {
  const resumeData = JSON.parse(localStorage.getItem('resumeData'));
  if (resumeData) {
    try {
      const contentObj = JSON.parse(resumeData.content);
      const form = document.getElementById('userForm');
      if (form) {
        for (const key in contentObj) {
          const input = form.querySelector(`[name="${key}"]`);
          if (input) {
            if (input.type === 'radio') {
              const radio = form.querySelector(`[name="${key}"][value="${contentObj[key]}"]`);
              if (radio) {
                radio.checked = true;
              }
            } else if (input.tagName === 'SELECT') {
              const option = input.querySelector(`option[value="${contentObj[key]}"]`);
              if (option) {
                option.selected = true;
              }
            } else {
              input.value = contentObj[key];
            }
          }
        }
      }
    } catch (error) {
      console.error('解析 content 字段时出错:', error);
      alert('解析简历数据时出错，请检查数据格式');
    }
  }
};